import { Modal, Form, Input, message, Select } from 'antd';
import React, { useEffect } from 'react';
import { addDataSource, testDataSource, updateDataSource } from '@/services/dataSourceService';

interface Props {
  visible: boolean;
  dataSource?: DataSourceType.DataSource;
  onCancel: () => void;
  onSuccess: () => void;
}

/**
 * 数据源弹窗表单
 * @constructor
 */
const DataSourceModal: React.FC<Props> = (props) => {
  const { visible, dataSource, onCancel, onSuccess } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible && dataSource) {
      form.setFieldsValue(dataSource);
    }
  }, [visible]);

  const onFinish = async (values: any) => {
    // 测试连接
    try {
      await testDataSource(values);
      message.success('连接测试成功');
    } catch (e) {
      message.error('连接测试失败');
      return;
    }

    // 提交
    if (dataSource) {
      await updateDataSource({
        ...values,
        id: dataSource.id,
      });
      message.success('更新成功');
    } else {
      await addDataSource(values);
      message.success('创建成功');
    }
    onSuccess();
  };

  const dbTypes = [
    { label: 'MySQL', value: 'MySQL' },
    { label: 'Oracle', value: 'Oracle' },
    { label: 'PostgreSQL', value: 'PostgreSQL' },
    { label: 'SQL Server', value: 'SQL Server' },
  ];

  return (
    <Modal
      title={dataSource ? '编辑数据源' : '新增数据源'}
      open={visible}
      onCancel={onCancel}
      onOk={() => {
        form.submit();
      }}
      destroyOnClose
    >
      <Form form={form} layout="vertical" onFinish={onFinish}>
        <Form.Item
          name="name"
          label="数据源名称"
          rules={[{ required: true, message: '请输入数据源名称' }]}
        >
          <Input placeholder="请输入数据源名称" />
        </Form.Item>
        <Form.Item
          name="dbType"
          label="数据库类型"
          rules={[{ required: true, message: '请选择数据库类型' }]}
        >
          <Select options={dbTypes} placeholder="请选择数据库类型" />
        </Form.Item>
        <Form.Item
          name="url"
          label="连接地址"
          rules={[{ required: true, message: '请输入连接地址' }]}
        >
          <Input placeholder="例如: jdbc:mysql://localhost:3306" />
        </Form.Item>
        <Form.Item
          name="dbName"
          label="数据库名称"
          rules={[{ required: true, message: '请输入数据库名称' }]}
        >
          <Input placeholder="请输入数据库名称" />
        </Form.Item>
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DataSourceModal;
